package com.chixing.dao.impl;

import com.chixing.dao.DBConn;
import com.chixing.dao.DepartmentDao;
import com.chixing.pojo.Department;

import java.sql.*;

public class DepartmentDaoImpl implements DepartmentDao {




    @Override
    public Department selectByPrimaryKey(int deptno) { //10
        Connection connection = DBConn.getConnection();
        PreparedStatement pstmt= null;
        ResultSet rs = null;
        Department department = null;

        String sql = "select deptno,dname,loc from dept where deptno = ?";
        try {
            pstmt =  connection.prepareStatement(sql);
            pstmt.setInt(1,deptno);
            rs = pstmt.executeQuery();
            while(rs.next()){
                deptno = rs.getInt(1);   // 10
                String deptName = rs.getString(2); // 财务部
                String deptLoc = rs.getString(3); //苏州

                department = new Department(deptno,deptName,deptLoc);
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally { // close rs ,pstmt, conn
            if(rs!=null) {
                try {
                    rs.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if(pstmt !=null) {
                try {
                    pstmt.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            DBConn.closeConnection();
        }

        return department;
    }




    @Override
    public int insert(Department department) {
        //1. 连接数据库
        Connection connection = DBConn.getConnection();
        PreparedStatement pstmt = null;
        int rows = 0;
        // 2. 执行sql语句
        String sql ="insert into dept values(?,?,?)";
        try {
            pstmt =   connection.prepareStatement(sql);

            pstmt.setInt(1,department.getDeptNo());
            pstmt.setString(2,department.getDeptName());
            pstmt.setString(3,department.getDeptLocation());

           rows = pstmt.executeUpdate();

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally { //close pstmt ,conn
            if(pstmt !=null) {
                try {
                    pstmt.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            DBConn.closeConnection();

        }

        return rows;
    }

    @Override
    public int delete(int deptno) {
        return 0;
    }

    @Override
    public int update(Department department) {
        return 0;
    }
}
